<?php


namespace EchoPHP\Rabbitmq\Query;


use EchoPHP\Facades\RabbitMq;

class QueuePublisher {
    protected $rabbitmqConnection;

    public function __construct(string $name) {
        $this->rabbitmqConnection = RabbitMq::connect($name);
    }

    /**
     * 发布消息
     * @param array $messages $messages 发送的消息实体 [['message'=>'消息实体','routekey'=>'路由键(可为空)', 'attributes' => ['消息的附加属性,如消息头类型等']]]
     * @return bool
     * @throws \AMQPChannelException
     * @throws \AMQPConnectionException
     * @throws \AMQPExchangeException
     */
    public function publish(array $messages) {
        if (empty($messages)) {
            return true;
        }
        $exchange = $this->rabbitmqConnection->getExchange();

        foreach ($messages as $message) {
            if (is_array($message['message'])) {
                $data = json_encode($message['message']);
            } else {
                $data = (string)$message['message'];
            }
            //使用匿名交换机则路由绑定需要直接指定为队列名称
            $routeKey = isset($message['routekey']) && !empty($message['routekey']) ? $message['routekey'] : '';
            $attributes = $message['attributes'] ?? [];
            $attributes = array_intersect_key($attributes, [
                'content_type' => '', 'content_encoding' => '', 'message_id' => '',
                'user_id' => '', 'app_id' => '', 'delivery_mode' => '',
                'priority' => '', 'timestamp' => '', 'expiration' => '',
                'type' => '', 'reply_to' => '', 'headers' => '',
            ]);
            $exchange->publish($data, $routeKey, AMQP_NOPARAM, $attributes);
        }
        return true;
    }
}